<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #tableBeforeButtons>
        <a-button type="primary" @click="addVisible = true">新增</a-button>
        <a-button type="primary" @click="handelShowUp">批量导入</a-button>
      </template>
      <template #total="{ record }">
        <div>
          {{ record.total }}
          <a-popover>
            <a-link>明细</a-link>
            <template #content>
              <a-table :columns="columnsMingxi" :data="record.zd" column-resizable :pagination="false">
                <template #pay_real_price="{ record }">
                  <a-link>
                    {{ (record.pay_real_price - 0).toFixed(2) }}
                  </a-link>
                </template>

              </a-table>
            </template>
          </a-popover>
        </div>
      </template>
      <template #dept_id="{ record }">
        <div class="ellipsis">{{ getUser(record.dept_id) }}</div>
      </template>
      <template #operationBeforeExtend="{ record }">
        <a-link @click="handlecaozuoMb(record)" :style="{ color: record.status == 1 ? '' : 'red' }">{{ record.status ==
          1 ?
          '已支付' : '未支付' }}</a-link>
      </template>
    </ma-crud>

    <!-- 新增 -->
    <a-drawer v-model:visible="addVisible" @cancel="addVisible = false" :width="1920" :footer="false">
      <template #title> 新增 </template>
      <recordAdd v-if="addVisible" @cell="handleCell"></recordAdd>
    </a-drawer>

    <!-- 导入 -->
    <a-modal :mask-closable="false" v-model:visible="showUpload" title="导入Excel" @cancel="handleShow" :width="600"
      :footer="false">
      <div style="padding: 8px 10px; " v-if="showUpload">
        <a-upload :file-list="fileList" draggable :action="env.VITE_APP_OPEN_PROXY === 'true'
          ? env.VITE_APP_PROXY_PREFIX + '/financial/payOrderRecord/import'
          : env.VITE_APP_BASE_URL + '/financial/payOrderRecord/import'
          " :headers="{ Authorization: `Bearer ${token}` }" :on-before-upload="beforeUpload" :limit="1" :data="{
            // transport_type: yunshuId,
            // serve_type: fuwuId,
            // butt_type: duijieId,
            // dept_id: yonghuId,
          }" @success="handleSuccess" />
      </div>
    </a-modal>

    <!-- 预览预计导入的数据 -->
    <a-modal :mask-closable="false" v-model:visible="showYuji" title="确认导入数据" @cancel="handleYujiCel" :width="1400"
      ok-text="确认导入" :footer="false">
      <a-table :summary="summary" :columns="columnsEpor" row-key="id" :bordered="{ wrapper: true, cell: true }"
        :data="yujiList" @selection-change="handleSelChange" :pagination="false">
      </a-table>
      <div style="display: flex; justify-content: flex-end; margin-top: 2%">
        <a-popconfirm @ok="handleYujiSucc" content="是否确认选中的账单收费?确认后将生成一笔待支付账单">
          <a-button type="primary" :loading="yujiloading">确认导入</a-button>
        </a-popconfirm>
      </div>
    </a-modal>


    <a-modal :mask-closable="false" v-model:visible="zhifuShow" title="支付" @cancel="quxiaozhifu" :width="600"
      :on-before-ok="handelzhifuOk">
      <div class="" style="margin-bottom: 2%;padding-left: 24px;height: 300px;">
        <div class="flex align_center" style="margin-bottom: 2%;">
          <div style="width: 80px;">结算方式：</div>
          <a-radio-group v-model="jiesuan" :options="jiesuanOptions" />
        </div>
        <div v-if='jiesuan == "3"'>
          <div style="display: flex;align-items: center;margin-bottom: 2%;">
            <div style="width: 80px;">支付方式</div>
            <a-radio-group v-model="zhifu" :options="zhifuOptions" />
          </div>
        </div>
        <div v-if="jiesuan == '1'" style="margin-bottom: 2%;">
          <div style="margin-bottom: 2%;">实际付款金额：{{ formData.total.toFixed(2) }}元
          </div>
          <!-- <div>当前可用余额：{{ availableAmount }}元</div> -->
        </div>
        <div style="display: flex;align-items: center;margin-bottom: 2%;">
          <div style="width: 80px;">支付时间</div>
          <a-date-picker style="width: 100%; " show-time v-model="pay_date" format="YYYY-MM-DD HH:mm:ss" />
        </div>
      </div>
    </a-modal>


  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import financialPayOrderRecord from '@/api/financial/financialPayOrderRecord'
import recordAdd from "./add.vue"
import { Message } from '@arco-design/web-vue'
import tool from '@/utils/tool'
import { request } from "@/utils/request.js";
import * as common from '@/utils/common'

onMounted(() => {
  getKehu()
})

const crudRef = ref()
const addVisible = ref(false)

const numberOperation = (newValue, id, numberName) => {
  financialPayOrderRecord.numberOperation({ id, numberName, numberValue: newValue }).then(res => {
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })
}

const switchStatus = (statusValue, id, statusName) => {
  financialPayOrderRecord.changeStatus({ id, statusName, statusValue }).then(res => {
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })
}
const handleCell = () => {
  addVisible.value = false
  crudRef.value.refresh()
}

const options = reactive({
  id: 'flyos_financial_pay_order_record',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  operationColumnWidth: 100,
  operationWidth: 160,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: financialPayOrderRecord.getList,
  recycleApi: financialPayOrderRecord.getRecycleList,
  add: {
    show: false,
    api: financialPayOrderRecord.save,
    auth: ['financial:payOrderRecord:save']
  },
  edit: {
    show: false,
    api: financialPayOrderRecord.update,
    auth: ['financial:payOrderRecord:update']
  },
  delete: {
    show: false,
    api: financialPayOrderRecord.deletes,
    auth: ['financial:payOrderRecord:delete'],
    realApi: financialPayOrderRecord.realDeletes,
    realAuth: ['financial:payOrderRecord:realDeletes']
  },
  recovery: {
    show: false,
    api: financialPayOrderRecord.recoverys,
    auth: ['financial:payOrderRecord:recovery']
  },
  import: {
    show: false,
    url: 'financial/payOrderRecord/import',
    templateUrl: 'financial/payOrderRecord/downloadTemplate',
    auth: ['financial:payOrderRecord:import']
  },
  export: {
    show: false,
    url: 'financial/payOrderRecord/export',
    auth: ['financial:payOrderRecord:export']
  }
})

const columnsMingxi = ref([
  {
    title: "运单号",
    dataIndex: "prediction.yundanhao",
  },
  {
    title: "车号",
    dataIndex: "prediction.car_no",
  },
  {
    title: "原票号",
    dataIndex: "prediction.ticket_number",
  },
  {
    title: "箱号",
    dataIndex: "prediction.box",
  },
  {
    title: "客户",
    dataIndex: "prediction.dept.name",
    slotName: 'name'

  },
  {
    title: "品名",
    dataIndex: "prediction.goods_name",
  },
  {
    title: "实际付款金额",
    dataIndex: "pay_real_price",
    slotName: 'pay_real_price'
  },
])

const getKehu = () => {
  request({
    url: 'system/dept/remote',
    method: "post",
  }).then(res => {
    kehuList.value = res.data
  })
}

const getUser = (id) => {
  let arr = kehuList.value.filter(item => item.id == id)
  if (arr.length) return arr[0].name
  return "多客户运单"
}

const kehuList = ref([])

const columns = reactive([
  {
    title: "",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入"
    }
  },
  {
    title: "客户",
    dataIndex: "dept_id",
    formType: "select",
    width: 180,
    search: true,
    dict: {
      // 远程通用接口请求，新版代码生成都有一个 remote 接口
      remote: "system/dept/remote",
      // 指定组件接收的props
      props: { label: "name", value: "id" },
      // 开启分页
      openPage: false,
      // 远程请求配置项
      remoteOption: {
        // 按用户名排序
        sort: { id: "desc" }, // 如果不指定排序方式，默认为正序排序
        // 设置查询的字段
        select: ["id", "name"],
        // 设置数据过滤
        filter: {
          type: ["=", 2],
          status: ['=', 1]
        },
        // 关联模型
        relations: [],
      },
      translation: true
    },
    commonRules: {
      required: true,
      message: "请选择客户"
    }
  },
  {
    title: "运单数量",
    dataIndex: "prediction_num",
    formType: "input"
  },
  {
    title: "总金额",
    dataIndex: "total",
    formType: "input"
  },
  {
    title: "操作人",
    dataIndex: "created_by",
    formType: "select",
    search: true,
    dict: {
      url: "system/user/index",
      params: {
        page: 1,
        pageSize: 2000
      },
      props: { label: "nickname", value: "id" },
      translation: true
    },
    commonRules: {
      required: true,
      message: "请选择操作人"
    }
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "range",
    align: "center",
    width: 180,
    search: true,
    addDisplay: false,
    editDisplay: false,
    sortable: {
      sortDirections: ["ascend", "descend"],
      sorter: true,
    },
    showTime: true,
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "创建人",
    dataIndex: "created_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "更新人",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  }
])

const env = ref(import.meta.env);
const token = ref(tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX));
const showUpload = ref(false)
const showYuji = ref(false);
const yujiloading = ref(false)
const selectedKeys = ref([]);
const yujiList = ref([]);
const payOrderId = ref([])
const zhifuShow = ref(false)
const zhifu = ref('3')
const jiesuan = ref('')
const opening_bank = ref()
const account = ref()
const account_name = ref()
const record_id = ref("")


const jiesuanOptions = ref([
  {
    label: "现结",
    value: "3",
  },
  {
    label: "周期结算",
    value: "2",
  },
  {
    label: "预付款",
    value: "1",
  }
])

const zhifuOptions = ref([
  { label: '对公转账', value: '3' },
  { label: '现金', value: '2' },
  { label: '惠支付', value: '1' },
])

// 数据
const formData = reactive({
  newData: [],
  total: 0
})
// 数据字段
const form = reactive({
  caozuo: "",
  yundanhao: "",
  car_no: "",
  box: "",
  price_type: "",
  pay_name: "",
  pay_price: "",
  pay_real_price: "",
  remark: "",
  pay_dept_id: "",
  type: "1"
})


const columnsEpor = reactive([
  {
    title: "运单号",
    dataIndex: "yundanhao",
    align: "center",
    ellipsis: true,
    fixed: "left",
    width: 140,
    tooltip: true,
  },
  {
    title: "车号",
    dataIndex: "car_nos",
    align: "center",
    ellipsis: true,
    fixed: "left",
    width: 140,
    tooltip: true,
  },
  {
    title: "箱号",
    dataIndex: "box",
    align: "center",
    ellipsis: true,
    fixed: "left",
    width: 140,
    tooltip: true,
  },
  {
    title: "计费类型",
    dataIndex: "price_type",
    align: "center",
    ellipsis: true,
    width: 100,
    tooltip: true,
  },
  {
    title: "计费名称",
    dataIndex: "pay_name",
    align: "center",
    ellipsis: true,
    width: 100,
    tooltip: true,
  },
  {
    title: "原金额",
    dataIndex: "pay_price",
    align: "center",
    ellipsis: true,
    width: 140,
    tooltip: true,
  },
  {
    title: "实际付款金额",
    dataIndex: "pay_real_price",
    align: "center",
    ellipsis: true,
    width: 100,
    tooltip: true,
  },
  {
    title: "付款人",
    dataIndex: "pay_dept_id",
    align: "center",
    ellipsis: true,
    width: 100,
    tooltip: true,
  },
  {
    title: "备注",
    dataIndex: "remark",
    align: "center",
    ellipsis: true,
    width: 100,
    tooltip: true,
  },
])

const pay_date = ref(tool.dateFormat(
  Math.round(new Date().getTime() / 1000).toString(),
  "yyyy-MM-dd hh:mm:ss"
))

const objcetData = ref({
  prediction_id: '',
  pay_dept_id: '',
  detail: [
    {
      type: 1,
      price_type: '',
      pay_name: '',
      no_tax_price: '',
      tax_price: '',
      pay_real_price: '',
      remark: '',
      caozuo: '',
    }, {
      type: 2,
      price_type: '',
      pay_name: '',
      no_tax_price: '',
      tax_price: '',
      pay_real_price: '',
      remark: '',
      caozuo: '',
    }
  ]
})

const zhifuData = ref({
  prediction_id: '',
  pay_dept_id: '',
  pay_items_json: [],
})

// 导入的文件列表
const fileList = reactive([])
const handelShowUp = () => {
  showUpload.value = true;
};
// 关闭弹窗
const handleShow = () => {
  showUpload.value = false;
};
// 导入之前处理
const beforeUpload = () => {
  return true;
};
// 预报单导入成功
const handleSuccess = (res) => {
  if (res.response.code == 200 && res.response.data.length > 0) {
    showUpload.value = false;
    showYuji.value = true;
    yujiloading.value = false;
    let _data = res.response.data.filter(item => item.yundanhao)
    yujiList.value = _data;
    // 获取运单号列表
    let dataArr = []
    let yundanhaoList = _data.map(item => {
      return item.yundanhao
    })
    const uniqueArr = [...new Set(yundanhaoList)]
    // 根据运单号把数据分组
    uniqueArr.forEach(item => {
      let newArr = []
      let arr = _data.filter(item1 => item1.yundanhao == item)
      // 获取箱号列表
      let xianghaoList = arr.map(item1 => item1.box)
      // 根据箱号把数据分组
      let xianghaoArr = [...new Set(xianghaoList)]
      xianghaoArr.forEach(item1 => {
        let arr1 = arr.filter(item2 => item2.box == item1)
        newArr.push(arr1)
      })
      dataArr.push(newArr)
    })
    formData.newData = dataArr
  } else {
    Message.error("数据异常！无数据或格式错误")
  }
};


// 成功   导入
const handleYujiSucc = () => {
  formData.total = 0
  yujiloading.value = true
  yujiList.value.forEach((item, index) => {
    formData.total += parseFloat(item.pay_real_price)
  })
  request({
    url: 'financial/payOrder/saveAllImport',
    method: 'post',
    data: {
      ...formData,
      oldData: yujiList.value
    }
  }).then(res => {
    if (res.code == 200) {
      zhifuShow.value = true
      isTable.value = false
      payOrderId.value = res.data.ids
      record_id.value = res.data.record_id
      getaccount()
    }
  })
  // console.log(formData);
  yujiloading.value = false

};

const handleYujiCel = () => {
  // next.value = 1
  showYuji.value = false;
};

// 选择的
const handleSelChange = (res) => {
};

const summary = ({ columns, data }) => {
  let countData = {
    pay_real_price: 0,
  };
  data.forEach(record => {
    countData.pay_real_price += parseFloat(record.pay_real_price);
  })

  return [{
    yundanhao: '合计',
    pay_real_price: countData.pay_real_price,
  }]
}

const getaccount = () => {
  request({
    url: "system/dataDict/index",
    method: "get",
    params: {
      page: 1,
      pageSize: 10,
      type_id: 41
    },
  }).then((res) => {
    opening_bank.value = res.data.items[0].value
    account.value = res.data.items[1].value
    account_name.value = res.data.items[2].value
  });
}

const handelzhifuOk = async () => { // 支付成功
  let obj = {}
  // 更新时间
  pay_date.value = tool.dateFormat(
    Math.round(new Date().getTime() / 1000).toString(),
    "yyyy-MM-dd hh:mm:ss"
  )
  obj.record_id = record_id.value
  if (jiesuan.value == '1' || jiesuan.value == '2') {
    obj.pay_type = jiesuan.value == 1 ? 'money' : 'periodic'
    obj.ids = payOrderId.value
    obj.pay_date = pay_date.value
  }
  if (jiesuan.value == '3') {
    obj.pay_type = 'now_pay'
    obj.ids = payOrderId.value
    obj.now_pay_type = zhifu.value
    obj.transfer_proof_images = ""
    obj.payment_method = zhifu.value
    obj.settlement_method = 1
    obj.pay_date = pay_date.value
    obj.notes = ''
    obj.dept_id = zhifuData.value.pay_dept_id    // 公司
    obj.opening_bank = opening_bank.value    // 开户行
    obj.account = account.value    // 收款账户
    obj.account_name = account_name.value    // 开户行名称
  }
  let res = await request({
    url: "financial/payOrder/payBatch",
    // url:isTable.value?"financial/payOrder/payBatch": "financial/payOrder/pay",
    method: "post",
    data: obj,
  })
  if (res.code == 200) {
    Message.success(res.message);
    showYuji.value = false
    isTable.value = false
    record_id.value = ""
    crudRef.value.refresh()
  } else {
    Message.error(res.message)
  }

}

const quxiaozhifu = () => {
  zhifuShow.value = false
}

const isTable = ref(false)

const handlecaozuoMb = (e) => {
  if (e.status == 0) {
    zhifuShow.value = true
    payOrderId.value = JSON.parse(e.pay_ids)
    isTable.value = true
    record_id.value = e.id
    formData.total = parseFloat(e.total)
  }
}



</script>
<script>export default { name: 'financial:payOrderRecord' } </script>